package 二叉树;

public class 完全二叉树的节点个数 {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //它会一直递归下去的，直到只有最边边的节点，因为是一开始遍历到最下面，会一直叠加上去的
    public int countNodes(TreeNode root){
        if (root == null) return 0;
        int leftdepth = getdepth(root.left);
        int rightdepth = getdepth(root.right);
        if (leftdepth == rightdepth ){
            //左子树是满二叉树
            // 2^leftDepth其实是 （2^leftDepth - 1） + 1 ，左子树 + 根结点
            return (1<<leftdepth) + countNodes(root.right);
        }else {
            //右子数是满二叉树
            return (1<<rightdepth) + countNodes(root.left);
        }

    }
    private int getdepth(TreeNode root){
        int depth = 0;
        while (root!=null){
            root = root.left;
            depth++;
        }
        return depth;
    }
}
